﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ElingOA6_Admin_DSJCJ.Common;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Configuration;

namespace ElingOA5_AdminSysMan.Web.fckeditor.editor.plugins.easyUpload.fck_video
{
    public partial class fck_file_upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = 0;
            if (!IsPostBack)
            {
                upload();
            }
        }

        // Response.Write("successed|ok");//上传成功：Response.Write("successed|文件url"); 上传失败:Response.Write("error");
        private void upload() {
            try
            {
                System.Web.HttpFileCollection uploadFiles = Request.Files;
                System.Web.HttpPostedFile theFile;
                if (uploadFiles.Count>0)
                {
                    theFile = uploadFiles[0];
                    if (null!=theFile)
                    {
                        if (uploadFiles.GetKey(0).ToUpper() == "FILEDATA")//swfupload控件中的文档
                        {
                            string _strUrl = GenerateUtil.GetRootPath(this.Page) + "Publish/" + OperateSession.get("EntityNo") + "/Video/";
                            string  _strUploadUrl = Server.MapPath(_strUrl);
                            GenerateUtil.addfolder(_strUrl);
                            //文件后缀名
                            string _backname = theFile.FileName.Substring(theFile.FileName.LastIndexOf('.') + 1);
                            string fname = GenerateUtil.GenerateStringId() + "." + _backname;
                            string _filenameWithoutBack = fname.Substring(0, fname.LastIndexOf('.'));//文件名称（不包括后缀名）
                            theFile.SaveAs(_strUploadUrl + fname);
                            string _strVideoHtml = string.Empty;
                            if (_backname.ToLower() != "flv")
                            {
                                //转换成flv
                                string videoPath = _strUploadUrl + fname;
                                string targetPath = _strUploadUrl + _filenameWithoutBack + ".flv";

                                if (MChangeFilePhy(videoPath, targetPath))//转换成功
                                {
                                    delVideoFile(videoPath);
                                    _strVideoHtml = groupVideoHtml(_strUrl + _filenameWithoutBack + ".flv");
                                    Response.Write("successed|" + _strVideoHtml);
                                    Response.End();
                                }
                                else
                                {
                                    delVideoFile(videoPath);
                                    Response.Write("error");
                                    Response.End();
                                }


                            }
                            else {
                                _strVideoHtml = groupVideoHtml(_strUrl + fname);
                                Response.Write("successed|" + _strVideoHtml);
                                Response.End();
                            }
                            
                        }
                    }

                }

            }
            catch (Exception)
            {             
                
            }
        }

        
        //组合显示视频的HTML代码
        private string groupVideoHtml(string _strUrl)
        {
            string _strVideoWidth = ConfigurationManager.AppSettings["video_width"].ToString();
            string _strVideoHeight = ConfigurationManager.AppSettings["video_height"].ToString();
            string _strAllPath = GenerateUtil.GetRootPath(this.Page);
            StringBuilder sbr = new StringBuilder();
            sbr.Append("<object id=\"player\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" name=\"player\"  width=\"");
            sbr.Append(_strVideoWidth);
            sbr.Append("\" height=\"");
            sbr.Append(_strVideoHeight);
            sbr.Append("\">");

            sbr.Append("<param name=\"movie\" value=\"");
            sbr.Append(_strAllPath);
            sbr.Append("Scripts/jwplayer/player.swf\" />");

            sbr.Append("<param name=\"allowfullscreen\" value=\"true\" />");

            sbr.Append("<param name=\"allowscriptaccess\" value=\"always\" />");

            sbr.Append("<param name=\"flashvars\" value=\"file=");
            sbr.Append(_strUrl);
            sbr.Append("&autostart=true\" />");

            sbr.Append("</object>");

            return sbr.ToString();
        }



        //删除转换为flv文件的原文件
        public void delVideoFile(string _strUrl) {
            GenerateUtil.DeleteFileJD(_strUrl);
        }


        #region //运行mencoder的视频解码器转换(这里是(绝对路径))
        public bool MChangeFilePhy(string vFileName, string flv_file)
        {
            string tool = Server.MapPath(@"~/mpplayer\mencoder.exe");//HttpContext.Current.Server.MapPath(PublicMethod.mencodertool);
            //string mplaytool = HttpContext.Current.Server.MapPath(PublicMethod.ffmpegtool);

            if ((!System.IO.File.Exists(tool)) || (!System.IO.File.Exists(vFileName)))
            {
                return false;
            }
            //截图的尺寸大小,配置在Web.Config中,如:<add   key="CatchFlvImgSize"   value="240x180"   />   
            //string FlvImgSize = PublicMethod.sizeOfImg;

            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(tool);

            // FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            FilestartInfo.CreateNoWindow = true;//不显示dos命令行窗口 
            FilestartInfo.RedirectStandardOutput = true;// 
            FilestartInfo.RedirectStandardInput = true;// 
            StringBuilder commend = new StringBuilder();
            FilestartInfo.UseShellExecute = false;//是否指定操作系统外壳进程启动程序 

            //commend.Append(@"D:\vdtest\mpplayer\mencoder ");
            commend.Append("\"" + vFileName + "\"");

            commend.Append(" -of");
            commend.Append(" lavf");
            commend.Append(" -oac");
            commend.Append(" mp3lame");
            commend.Append(" -lameopts");
            commend.Append(" abr:br=56");
            commend.Append(" -ovc");
            commend.Append(" lavc");
            commend.Append(" -lavcopts");
            commend.Append(" vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:dia=4:cmp=6:vb_strategy=1");
            commend.Append(" -vf");
            //commend.Append(" scale=512:-3");
            commend.Append(" scale=0:0");
            commend.Append(" -ofps");
            commend.Append(" 12");
            commend.Append(" -srate");
            commend.Append(" 22050");

            commend.Append(" -o ");
            commend.Append("\"" + flv_file + "\"");
            FilestartInfo.Arguments = commend.ToString();// " " + vFileName + " -o " + flv_file + " -of lavf -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=200:mbd=2:mv0:trell:v4mv:cbp:last_pred=1:dia=-1:cmp=0:vb_strategy=1 -vf scale=0:0 -ofps 12 -srate 22050";
            try
            {
                Process p = Process.Start(FilestartInfo);
                StreamReader reader = p.StandardOutput;//截取输出流 
                while (!reader.EndOfStream)
                {
                    string tt = reader.ReadLine();
                }
                p.WaitForExit();//等待程序执行完退出进程 
                p.Close();//关闭进程 
                reader.Close();//关闭流 
            }
            catch
            {
                return false;
            }
            //
            return true;
        }
        #endregion



    }
}